package db.day04;

import com.mysql.jdbc.Driver;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {


    private static  String url = null;
    private static  String username = null;
    private static  String password = null;
    private static  String driverClassName = null;

    static {

        try {
            // 获取文件输入流
            FileInputStream fileInputStream = new FileInputStream("jdbc.properties");

            Properties properties = new Properties();
            // 装载
            properties.load(fileInputStream);

            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            driverClassName = properties.getProperty("driverClassName");

        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    // 获取连接
    public static Connection getConnection(){



        Connection connection = null;

        try {
            // 加载驱动 com.mysql.cj.jdbc.Driver
            Class.forName(driverClassName);

            // 获取连接对象
            connection = DriverManager.getConnection(url, username, password);

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return connection;
    }


    // 获取连接
    public static Statement getStatement(){



        Statement statement = null;

        try {
            // 加载驱动 com.mysql.cj.jdbc.Driver
            Class.forName(driverClassName);

            // 获取连接对象
            Connection connection = DriverManager.getConnection(url, username, password);

            statement = connection.createStatement();

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return statement;
    }


    // 关闭资源
    public static void releaseSources(Connection connection, Statement statement, ResultSet resultSet){

        // 关闭ResultSet
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        // 关闭statement
        if (statement != null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        // 关闭connection
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}
